<template>
  <div class="detail-container">
    <div class="detail-card">
      <h1 class="title">{{ articleData.title }}</h1>
      
      <div class="meta-info">
        <span>发布时间：{{ formatDate(articleData.published_at) }}</span>
        <span>截止时间：{{ formatDate(articleData.deadline) }}</span>
        <span>发布人：{{ articleData.publisher?.user_name }}</span>
      </div>

      <div class="product-info">
        <div class="info-item">
          <span class="label">产品名称：</span>
          <span>{{ articleData.product_name }}</span>
        </div>
        <div class="info-item">
          <span class="label">产品分类：</span>
          <span>{{ articleData.product_category }}</span>
        </div>
        <div class="info-item">
          <span class="label">地区：</span>
          <span>{{ articleData.region }}</span>
        </div>
        <div class="info-item">
          <span class="label">价格：</span>
          <span class="price">{{ articleData.price_offer }}元/斤</span>
        </div>
        <div class="info-item">
          <span class="label">总量：</span>
          <span>{{ articleData.total_quantity }}斤</span>
        </div>
        <div class="info-item">
          <span class="label">剩余量：</span>
          <span>{{ articleData.remaining_quantity }}斤</span>
        </div>
      </div>

      <div class="content-section">
        <h2>公告详情</h2>
        <div v-html="articleData.content ? marked.parse(articleData.content) : ''"></div>
      </div>

      <!-- 按钮组 -->
      <div class="button-group">
        <el-button type="primary" @click="handleShowContact">获取联系方式</el-button>
        <el-button type="success" @click="handleGoToAIInfo">AI 咨询</el-button>
      </div>

      <!-- 农户输入数量部分 -->
      <div class="farmer-input-section">
        <h2>我要出售<span style="font-size:14px;color:#999;font-weight:500;">(单位/斤)</span></h2>
        <div class="input-group" v-if="store.userdata.role_name === 'farmer'">
          <el-input-number 
            v-model="farmerQuantity" 
            :min="1"
            :step="1"
            controls-position="right"
            placeholder="请输入数量"
          />
          <el-button type="primary" @click="handleSubmit" :disabled="!farmerQuantity">提交</el-button>
        </div>
        <p class="tip" v-if="store.userdata.role_name === 'farmer'">请输入您可以提供的数量，不能超过剩余收购量</p>
        <p class="prevent-tip" v-if="store.userdata.role_name === 'dealer'">此平台用于帮助农户和经销商进行农产品对接，经销商不能出售商品，仅可发布收购或前往出售页购买</p>
        <p class="prevent-tip" v-if="store.userdata.role_name === 'gov'">此平台用于帮助农户和经销商进行农产品对接，政府用户不能直接进行出售，需在"政府收售"页发布农产品出售</p>
      </div>

      <div class="actions">
        <el-button @click="handleBack">返回</el-button>
      </div>
    </div>

    <!-- 确认订单弹窗 -->
    <el-dialog v-model="showOrderDialog" title="确认订单" width="550px" center>
      <div class="buy-dialog">
        <div class="order-item">
          <el-icon><User /></el-icon>
          <div class="order-content">
            <span class="label">出售人：</span>
            <span class="value">{{ store.userdata.nick_name }}</span>
          </div>
        </div>
        <div class="order-item">
          <el-icon><ShoppingCart /></el-icon>
          <div class="order-content">
            <span class="label">产品名称：</span>
            <span class="value">{{ articleData.product_name }}</span>
          </div>
        </div>
        <div class="order-item">
          <el-icon><Goods /></el-icon>
          <div class="order-content">
            <span class="label">出售数量：</span>
            <span class="value">{{ farmerQuantity }}斤</span>
          </div>
        </div>
        <div class="order-item">
          <el-icon><Money /></el-icon>
          <div class="order-content">
            <span class="label">单价：</span>
            <span class="value price">￥{{ articleData.price_offer }}元/斤</span>
          </div>
        </div>
        <div class="order-item">
          <el-icon><Wallet /></el-icon>
          <div class="order-content">
            <span class="label">总金额：</span>
            <span class="value total-price">￥{{ (farmerQuantity * articleData.price_offer).toFixed(2) }}元</span>
          </div>
        </div>
        <div class="order-item">
          <div class="order-content remark-section">
            <span class="label"><el-icon><ChatDotRound /></el-icon>备注：</span>
            <el-input v-model="sellerRemark" type="textarea" :rows="3" placeholder="请输入备注" />
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="confirmSubmit">确认提交</el-button>
        <el-button @click="showOrderDialog = false">取消</el-button>
      </template>
    </el-dialog>
    
    <!-- 联系方式弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="联系方式"
      width="400px"
      center
    >
      <div class="contact-dialog">
        <div class="contact-item">
          <el-icon><User /></el-icon>
          <div class="contact-content">
            <span class="label">联系人：</span>
            <span class="value">{{ articleData.publisher?.user_name }}</span>
          </div>
        </div>
        <div class="contact-item">
          <el-icon><Phone /></el-icon>
          <div class="contact-content">
            <span class="label">联系电话：</span>
            <span class="value">{{ articleData.publisher?.phone }}</span>
          </div>
        </div>
        <div class="contact-item">
          <el-icon><Message /></el-icon>
          <div class="contact-content">
            <span class="label">电子邮箱：</span>
            <span class="value">{{ articleData.publisher?.email }}</span>
          </div>
        </div>
        <div class="contact-item">
          <el-icon><Location /></el-icon>
          <div class="contact-content">
            <span class="label">地址：</span>
            <span class="value">{{ articleData.publisher?.address }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useMainStore } from '@/stores';
import { User, Phone, Message, Location, ShoppingCart, Goods, Money, Wallet, ChatDotRound } from '@element-plus/icons-vue';
import { marked } from 'marked';

const route = useRoute();
const router = useRouter();
const store = useMainStore();
const articleData = ref({});
const farmerQuantity = ref(null);
const dialogVisible = ref(false);
const showOrderDialog = ref(false);
const sellerRemark = ref('');
const $axios = inject('$axios');
const $tools = inject('$tools')

// 从后端获取文章详情的方法
const fetchArticleDetail = async (id) => {
  try {
    const response = await $axios.get(`/article/id?article_id=${id}`);
    if (response.data.code === 200) {
      // 同步一下导航栏状态，直接外部进入的情况
      if(response.data.data.publisher.role=="dealer") store.changeView(1);
      else store.changeView(2)
      return response.data.data;
    } else {
      throw new Error(response.data.msg || '获取文章详情失败');
    }
  } catch (error) {
    console.error('获取文章详情错误:', error);
    $tools.alertMsg(error.message || '获取文章详情失败','error');
    return null;
  }
};

// 在组件挂载时获取数据
onMounted(async () => {
  const articleId = parseInt(route.params.id);
  
  // 优先使用 store 中的数据
  if (store.currentArticle?.article_id === articleId) {
    // 如果 store 中有数据，优先使用 store 中的数据
    articleData.value = store.currentArticle;
  } else {
    // 从 store 查找文章
    const article = store.findArticleById(articleId);
    if (article) {
      articleData.value = article;
      store.setCurrentArticle(article);
    } else {
      // 当 store 中没有数据时，从后端获取
      const fetchedArticle = await fetchArticleDetail(articleId);
      if (fetchedArticle) {
        articleData.value = fetchedArticle;
        store.setCurrentArticle(fetchedArticle);
      } else {
        router.push('/home/library');
      }
    }
  }
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 处理显示联系方式
const handleShowContact = () => {
  dialogVisible.value = true;
}

// 处理跳转到AI资讯
const handleGoToAIInfo = () => {
  // 设置导航栏状态为咨询室(索引3)
  sessionStorage.setItem('navView', 3)
  router.push({
    path: '/home/chat',
  });
}

// 使用依赖注入的方式获取axios实例，不再需要import

// handleSubmit方法修改为显示确认订单弹窗
const handleSubmit = () => {
  // 检查用户身份是否为经销商
  // if (store.userdata.role_name === "dealer") {
  //   $tools.alertMsg('此平台用于帮助农户和经销商进行农产品对接，经销商不能出售商品，仅可发布收购或去出售页购买','error',4000);
  //   return;
  // }
  // if (store.userdata.role_name === "gov") {
  //   $tools.alertMsg('此平台用于帮助农户和经销商进行农产品对接，政府用户不能直接进行出售，需在"政府收售"页发布农产品出售', 'error',4000)
  //   return;
  // }
  // 检查剩余数量
  const remainingQuantity = parseFloat(articleData.value.remaining_quantity);
  const requestQuantity = Number(farmerQuantity.value);

  if (isNaN(remainingQuantity) || isNaN(requestQuantity)) {
    $tools.alertMsg('数量格式错误','error');
    return;
  }

  if (requestQuantity > remainingQuantity) {
    $tools.alertMsg(`输入数量不能超过剩余收购量(${remainingQuantity}斤)，已调整为最大收购量`,'error');
    farmerQuantity.value = parseFloat(articleData.value.remaining_quantity);
    return;
  }
  
  // 显示确认订单弹窗
  showOrderDialog.value = true;
}

// 确认提交订单
const confirmSubmit = async () => {
  showOrderDialog.value = false;
  
  const requestData = {
    buyer_id: Number(articleData.value.publisher.user_id),
    items: [{
      product_id: Number(articleData.value.article_id),
      quantity: Number(farmerQuantity.value),
      product_type: "supply",
      remarks: sellerRemark.value || `响应${articleData.value.title}`
    }]
  };

  try {
    // 设置请求头
    const config = {
      headers: {
        'Content-Type': 'application/json',
        // 如果有token的话也加上
        // 'Authorization': `Bearer ${token}`
      }
    };

    
    const response = await $axios.post('/orders/supply', requestData, config);
    
    if (response.data.code === 200) {
      ElMessage.success('提交成功！订单已创建');
      // 重新获取文章数据以更新页面显示
      const updatedArticle = await fetchArticleDetail(articleData.value.article_id);
      if (updatedArticle) {
        articleData.value = updatedArticle;
        store.setCurrentArticle(updatedArticle);
        // 清空输入数量
        farmerQuantity.value = null;
      }
      // router.push('/home/library');
    } else {
      throw new Error(response.data.msg || '提交失败');
    }
  } catch (error) {
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    });

    // 根据不同错误类型显示不同提示
    if (error.response?.status === 400) {
      $tools.alertMsg('提交失败：数据格式错误或剩余数量不足','error');
    } else if (error.response?.status === 401) {
      $tools.alertMsg('请先登录','error');
    } else {
      $tools.alertMsg(error.response?.data?.msg || '提交失败，请稍后重试','error');
    }
  }
}


const handleBack = () => {
  router.back();
}
</script>

<style lang="less" scoped>
.detail-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;

  .detail-card {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .title {
      font-size: 24px;
      color: #333;
      margin-bottom: 16px;
    }

    .meta-info {
      display: flex;
      gap: 24px;
      color: #666;
      font-size: 14px;
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid #eee;
    }

    .product-info {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;
      margin-bottom: 24px;

      .info-item {
        display: flex;
        align-items: center;

        .label {
          min-width: 80px;
          color: #666;
        }

        .price {
          color: #ff4d4f;
          font-weight: bold;
        }
      }
    }

    .content-section {
      margin-bottom: 24px;

      h2 {
        color: #333;
        margin-bottom: 16px;
      }

      :deep(pre) {
        background-color: #f6f8fa;
        padding: 16px;
        border-radius: 6px;
        overflow-x: auto;
        margin: 10px 0;
        border: 1px solid #e1e4e8;
      }

      :deep(code) {
        font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
        font-size: 13px;
        tab-size: 4;
      }

      :deep(:not(pre) > code) {
        background-color: rgba(175, 184, 193, 0.2);
        padding: 0.2em 0.4em;
        border-radius: 3px;
        font-size: 85%;
      }

      :deep(p) {
        margin-bottom: 8px;
        color: #666;
        line-height: 1.6;
      }

      :deep(ul), :deep(ol) {
        margin-left: 20px;
        margin-bottom: 10px;
        color: #666;
      }

      :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
        margin-top: 5px;
        margin-bottom: 5px;
        color: #333;
      }
      :deep(h1){
        font-size: 1.6em;
        line-height: 1.6em;
      }
      :deep(h2){
        font-size: 1.5em;
        line-height: 1.5em;
      }
      :deep(h3){
        font-size: 1.4em;
        line-height: 1.4em;
      }
      :deep(h4){
        font-size: 1.3em;
        line-height: 1.3em;
      }
      :deep(h5){
        font-size: 1.2em;
        line-height: 1.2em;
      }
      :deep(h6){
        font-size: 1.1em;
        line-height: 1.1em;
      }

      :deep(table) {
        border-collapse: collapse;
        width: 100%;
        margin: 10px 0;
        display: block;
        overflow-x: auto;
 
        th, td {
          border: 1px solid #ddd;
          padding: 8px;
          text-align: left;
        }

        th {
          background-color: #f2f2f2;
        }
      }

      :deep(blockquote) {
        border-left: 4px solid #ddd;
        padding-left: 10px;
        color: #666;
        margin: 10px 0;
      }
    }

    .button-group {
      display: flex;
      gap: 16px;
      margin-bottom: 24px;
      justify-content: center;
    }

    .farmer-input-section {
      margin-bottom: 24px;
      padding: 20px;
      background: #f8f8f8;
      border-radius: 8px;

      h2 {
        font-size: 18px;
        color: #333;
        margin-bottom: 16px;
        span{
          font-size:14px;
          color:#999;
          font-weight:500;
        }
      }

      .input-group {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 8px;

        .unit {
          color: #666;
        }
      }

      .tip,.prevent-tip {
        font-size: 14px;
        color: #999;
        margin-top: 8px;
      }
      .prevent-tip{
        color: rgb(245, 9, 9)
      }
    }

    .actions {
      display: flex;
      justify-content: center;
      gap: 16px;
    }
  }
}

// 联系方式弹窗样式
.contact-dialog {
  padding: 10px 15px;
  
  .contact-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 10px;
    border-radius: 8px;
    background-color: #f8f8f8;
    transition: all 0.3s ease;
    
    &:hover {
      background-color: #e8f5e9;
      transform: translateX(5px);
    }
    
    .el-icon {
      font-size: 24px;
      color: #319A19;
      margin-right: 15px;
    }
    
    .contact-content {
      flex: 1;
      
      .label {
        color: #909399;
        font-size: 14px;
        margin-right: 8px;
      }
      
      .value {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }
  }
}

.buy-dialog {
  padding: 10px 15px;
  
  .order-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding: 10px;
    border-radius: 8px;
    background-color: #f8f8f8;
    transition: all 0.3s ease;
    
    &:hover {
      background-color: #f0f9eb;
      transform: translateX(5px);
    }
    
    .el-icon {
      font-size: 24px;
      color: #319A19;
      margin-right: 15px;
    }
    
    .order-content {
      flex: 1;
      
      .label {
        color: #909399;
        font-size: 14px;
        margin-right: 8px;
      }
      
      .value {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
      
      .price {
        color: #ff6b6b;
        font-weight: bold;
      }
      
      .total-price {
        color: #ff4757;
        font-weight: bold;
        font-size: 18px;
      }
      
      &.remark-section {
        display: flex;
        flex-direction: column;
        
        .label {
          margin-bottom: 8px;
          display: flex;
          align-items: center;
        }
        
        .el-textarea {
          margin-top: 5px;
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .detail-container {
    padding: 12px;

    .detail-card {
      padding: 16px;

      .meta-info {
        flex-direction: column;
        gap: 8px;
      }

      .product-info {
        grid-template-columns: 1fr;
      }

      .button-group {
        flex-direction: column;
        
        .el-button {
          width: 100%;
        }
      }

      .farmer-input-section {
        padding: 16px;
        
        .input-group {
          flex-direction: column;
          align-items: stretch;

          .el-input-number {
            width: 100%;
          }

          .el-button {
            width: 100%;
          }
        }
      }

      .actions {
        flex-direction: column;
        
        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style>